import getUserTempId from "@/utils/userTempId";

import { loginRequest, getUserInfoRequest, loginOutRequest } from "@/api";

//user的store模块化
const state = {
  getUserTempId: getUserTempId(),
  // 在本地存储中取token 如果没有则给一个空串 避免请求问题
  token: localStorage.getItem("user_token") || "",
  nickName: "",
};
const mutations = {
  SET_STATETOKEN(state, token) {
    state.token = token;
  },
  SET_STATENICKNAME(state, nickName) {
    state.nickName = nickName;
  },
  SET_STATEOUT(state) {
    state.token = "";
    state.nickName = "";
    //清除本地存储token
    localStorage.removeItem("user_token");
  },
};
const actions = {
  //登录获取token
  async getLogin({ commit }, userInfo) {
    const result = await loginRequest(userInfo);
    commit("SET_STATETOKEN", result.token);

    //做token的本地存储,防止用户刷新页面重新登录
    localStorage.setItem("user_token", result.token);
    //每次vuex中的state去本地存储中拿token
  },
  //携带token获取用户信息
  async getUserInfo({ commit }) {
    const result = await getUserInfoRequest();
    commit("SET_STATENICKNAME", result.nickName);
  },

  //退出登录请求
  async loginOut({ commit }) {
    await loginOutRequest();
    commit("SET_STATEOUT");
  },
};
const getters = {};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
